package cn.s1995.sloth.bizs.service.impl;

import cn.s1995.sloth.bizs.annotation.RedisLock;
import cn.s1995.sloth.bizs.constant.RedisKeyCst;
import cn.s1995.sloth.bizs.service.TestService;
import cn.s1995.sloth.common.core.util.R;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * TestServiceImpl
 *
 * @Author Lex
 * @Description
 * @Date 2023/11/21 14:06
 */
@Service
@Slf4j
public class TestServiceImpl implements TestService {

    @Data
    public static class PayParamREQ {
        /**
         * 用户id
         */
        @Schema(description = "用户id", hidden = true)
        private Long uid;

        /**
         * 支付方式：1.微信支付 2.支付宝 3.手动代付 4.paypal 5.google 6.apple 7.stripe
         */
        @NotNull(message = "支付方式不能为空")
        @Schema(description = "支付方式：1.微信支付 2.支付宝 3.手动代付 4.paypal 5.google 6.apple 7.stripe", required = true, example = "4")
        private Integer payMethod;

        /**
         * 订单号
         */
        @NotNull(message = "订单号不能为空")
        @Size(min = 1)
        @Schema(description = "订单号集合", required = true)
        private List<Long> orders;

    }

    @RedisLock(name = "goods", key = "#goodId")
    @Override
    public R deductCommodityInventory(String goodId, int num) {
        log.info("{}, 产品【{}】扣减库存:{}", Thread.currentThread().getName(), goodId, num);
        // 扣减库存操作
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("产品扣减库存完成");
        return R.ok("产品扣减库存完成");
    }

    @Override
    @RedisLock(name = RedisKeyCst.ORDER_CREATE, key = "#req.uid", expire = 30)
    @SneakyThrows
    public R createOrder(PayParamREQ req) {
        log.info("创建订单收到的信息:{}", req);
        Thread.sleep(req.uid * 1000);
        return R.ok(req);
    }

    @Override
    public void register(String phone, String nickName) {
        log.info("注册账户收到的信息:{},{}", phone, nickName);
        try {
            // 模拟业务过程
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("注册账户业务处理完");
    }


    public void lockTimeOut(String userId) {
        log.info("锁超时接收到的消息:{}", userId);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("锁超时业务处理完");
    }

    private String customLockTimeout(String userId) {
        log.info("自定义策略锁超时: {}", userId);
        return "自定义策略锁超时";
    }

}
